﻿using SBlogCore.Common.DispatchProxyIn;
using SBlogCore.Common.RemoteRequest.Models;
using System.Reflection;

namespace SBlogCore.Common.RemoteRequest.Proxys
{
    //https://blog.csdn.net/weixin_37648525/article/details/124222729
    [SkipScan]
    public class HttpDispatchProxy : GlobalDispatchProxy
    {
        protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
        {
            if (targetMethod==null)
            {
                throw new Exception("HTTP代理服务异常！");
            }
            var returnType = targetMethod.ReturnType;
            //判断是否为异步方法
            var isTask = targetMethod.ReturnType.GetMethod(nameof(Task.GetAwaiter))!=null;
            if (returnType.IsGenericType && isTask)
            {
                //如果是异步方法就将返回的数据类型拿出来
                returnType = returnType.GetGenericArguments().FirstOrDefault()!;
            }
            HttpClientPart clientPart = HttpClientPartFactory.Create(targetMethod, args);
            var responseMethod= typeof(HttpClientPart).GetMethod(nameof(HttpClientPart.SendAsync))?.MakeGenericMethod(returnType);
            //Invoke 参数1 调用方法所处的实例，参数2  方法所需要的参数
            dynamic task = responseMethod?.Invoke(clientPart, null);
            return task;
        }
    }

}
